import React, { useState, useEffect } from 'react'
import { Plus } from 'lucide-react'
import URLCard from './URLCard'
import { getUserFingerprint } from '../utils/userIdentification'

interface URLCardData {
  id: string
  name: string
  url: string
}

const defaultCards: URLCardData[] = [
  { id: 'default-1', name: 'ChatGPT', url: 'https://chat.openai.com' },
  { id: 'default-2', name: 'Google', url: 'https://www.google.com' },
  { id: 'default-3', name: 'X', url: 'https://x.com' },
  { id: 'default-4', name: 'YouTube', url: 'https://www.youtube.com' },
  { id: 'default-5', name: 'GitHub', url: 'https://github.com' },
]

const QuickLinks: React.FC = () => {
  const [cards, setCards] = useState<URLCardData[]>([])
  const [showAddForm, setShowAddForm] = useState(false)
  const [newCardName, setNewCardName] = useState('')
  const [newCardURL, setNewCardURL] = useState('')
  const [userFingerprint, setUserFingerprint] = useState<string | null>(null)

  useEffect(() => {
    const initializeUserData = async () => {
      const fingerprint = await getUserFingerprint()
      setUserFingerprint(fingerprint)
      const savedCards = localStorage.getItem(`urlCards_${fingerprint}`)
      if (savedCards) {
        setCards(JSON.parse(savedCards))
      } else {
        // If no saved cards, use default cards
        setCards(defaultCards)
      }
    }
    initializeUserData()
  }, [])

  useEffect(() => {
    if (userFingerprint && cards.length > 0) {
      localStorage.setItem(`urlCards_${userFingerprint}`, JSON.stringify(cards))
    }
  }, [cards, userFingerprint])

  const addCard = (e: React.FormEvent) => {
    e.preventDefault()
    if (newCardName && newCardURL) {
      const newCard: URLCardData = {
        id: Date.now().toString(),
        name: newCardName,
        url: newCardURL.startsWith('http') ? newCardURL : `https://${newCardURL}`,
      }
      setCards([...cards, newCard])
      setNewCardName('')
      setNewCardURL('')
      setShowAddForm(false)
    }
  }

  const deleteCard = (id: string) => {
    setCards(cards.filter(card => card.id !== id))
  }

  return (
    <div>
      <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-4 mb-4">
        {cards.map((card) => (
          <URLCard key={card.id} card={card} onDelete={deleteCard} />
        ))}
        {cards.length < 8 && (
          <button
            onClick={() => setShowAddForm(true)}
            className="flex flex-col items-center justify-center p-4 bg-white rounded-lg shadow hover:shadow-md transition-shadow"
          >
            <Plus size={24} className="mb-2" />
            <span className="text-sm">Add New</span>
          </button>
        )}
      </div>
      {showAddForm && (
        <form onSubmit={addCard} className="bg-white p-4 rounded-lg shadow">
          <input
            type="text"
            value={newCardName}
            onChange={(e) => setNewCardName(e.target.value)}
            placeholder="Name"
            className="w-full mb-2 p-2 border rounded"
            required
          />
          <input
            type="url"
            value={newCardURL}
            onChange={(e) => setNewCardURL(e.target.value)}
            placeholder="URL"
            className="w-full mb-2 p-2 border rounded"
            required
          />
          <div className="flex justify-end">
            <button
              type="button"
              onClick={() => setShowAddForm(false)}
              className="mr-2 px-4 py-2 text-gray-600 bg-gray-200 rounded"
            >
              Cancel
            </button>
            <button
              type="submit"
              className="px-4 py-2 text-white bg-blue-500 rounded"
            >
              Add
            </button>
          </div>
        </form>
      )}
    </div>
  )
}

export default QuickLinks